import React from 'react';
import { Form, Input, Select, Row, Col, DatePicker, message, Icon, Upload, Button } from 'antd';
import { connect } from 'dva';
import TableData from '../../components/tableDatas';
import orderStatus from '../../common/database';
import { getLoginToken } from '../../utils/utils';
import styles from './index.less';
import moment from 'moment';

const { Option } = Select;
const namespace = 'returnManagement';
/**
 *  登录界面
 */
@connect(({ loading, returnManagement }) => {
  return {
    //控制状态，绑定事件
    loading: loading.effects['returnManagement/fetch'],
    dataList: returnManagement.dataList,
    pagination: returnManagement.pagination
  };
})
@Form.create()
class All extends React.Component {
  state = {
    tips: [
      {
        id: 0,
        title: 'Estimated Refund',
        money: '$50.00'
      },
      {
        id: 1,
        title: 'Order payment',
        money: '$350.00'
      },
      {
        id: 2,
        title: 'Standard Delivery change',
        money: '-$50.00'
      },
      {
        id: 3,
        title: 'Return cost',
        money: '-$50.00'
      }
    ]
  };

  // 搜索
  handleSubmit(e) {
    e && e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        values.requestDate = values.requestDate ? values.requestDate.format('YYYY-MM-DD') : values.requestDate;
        this.props.dispatch({
          type: `${namespace}/fetch`,
          payload: { ...values, pageNum: 1 }
        });
      }
    });
  }
  // 清楚搜索框
  handleReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSubmit();
  };
  // 导入
  handleUpload(file, fileList) {
    console.log(fileList, '数据222', file);
    this.props.dispatch({
      type: `${namespace}/uploadTemplate`,
      payload: {
        file
      }
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, dataList, pagination, handleDrawer } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      }
    };

    const config = {
      rules: [{ type: 'object', required: false, message: 'Please select time!' }]
    };

    const columns = [
      {
        title: 'Order number',
        dataIndex: 'orderNumber',
        key: 'orderNumber',
        render: (text, record) => (
          <a
            className={styles.orderNumber}
            onClick={() => handleDrawer(record)}
            style={record.remind ? { color: '#B80B12' } : {}}
          >
            {record.remind ? <Icon type="bell" theme="filled" style={{ marginRight: 5 }} /> : null}
            {text}
          </a>
        )
      },
      {
        title: 'Return number',
        dataIndex: 'returnNo',
        key: 'returnNo'
      },
      {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        render: text => {
          if (!text) return '--';
          let target = orderStatus[text || 0];
          if (!target) return '--';
          let color = target.color;
          return (
            <div style={{ color }}>
              <span style={{ background: color }} className={styles.point}></span>
              {orderStatus[text].value}
            </div>
          );
        }
      },
      {
        title: 'Request date',
        dataIndex: 'createTime',
        key: 'createTime',
        sorter: true,
        render: text => <span>{moment(text).format('DD/MM/YYYY')}</span>
      },
      {
        title: 'Product',
        key: 'productName',
        dataIndex: 'productName'
      },

      {
        title: 'QTY',
        dataIndex: 'requestQty',
        key: 'requestQty'
      },
      {
        title: 'Carrier',
        dataIndex: 'carrier',
        key: 'carrier'
      },
      {
        title: 'Received',
        dataIndex: 'received',
        key: 'received'
      },
      {
        title: () => 'Refund',
        dataIndex: 'estimatedRefund',
        key: 'estimatedRefund',
        render: text => <span>${text && Number(text).toFixed(2)}</span>
      }
    ];

    const tableProps = {
      columns,
      dataSource: dataList,
      loading,
      pagination: {
        total: pagination.total,
        current: pagination.current,
        pageSize: pagination.pageSize,
        hideOnSinglePage: true,
        showQuickJumper: true,
        showSizeChanger: true
      },
      rowClassName: 'rows',
      rowKey: 'tables-index',
      onChange: (pagination, filters, sorter, extra) => {
        let sort = '';
        if (sorter.order) {
          sort = sorter.order === 'descend' ? 'DESC' : 'ASC';
        }
        this.props.dispatch({
          type: `${namespace}/fetch`,
          payload: {
            pageNum: pagination.current,
            pageSize: pagination.pageSize,
            sort
          }
        });
      }
    };
    const props = {
      name: 'file',
      action: `${process.env.apiTest}/order/import`,
      headers: {
        Authorization: getLoginToken() ? getLoginToken() : ''
      },
      showUploadList: false,
      onChange: file => {
        if (file.file.status === 'done') {
          const res = file.file.response;
          if (res.code === 200) {
            message.success(res.msg || 'Operation succeeded');
            this.props.dispatch({
              type: `${namespace}/fetch`
            });
          } else {
            message.error(res.msg || '失败');
          }
        }
      }
    };
    return (
      <div className={styles.formItem}>
        <Form {...formItemLayout} onSubmit={e => this.handleSubmit(e)}>
          <Row gutter={16}>
            <Col className="gutter-row" span={4}>
              <Form.Item label="Return number">{getFieldDecorator('returnNo', {})(<Input />)}</Form.Item>
            </Col>
            <Col className="gutter-row" span={4}>
              <Form.Item label="Request date">{getFieldDecorator('requestDate', config)(<DatePicker />)}</Form.Item>
            </Col>
            <Col className="gutter-row" span={4}>
              <Form.Item label="Status">
                {getFieldDecorator('status', {
                  initialValue: ''
                })(
                  <Select>
                    <Option value="">All</Option>
                    <Option value="0">{orderStatus[0].value}</Option>
                    <Option value="1">{orderStatus[1].value}</Option>
                    <Option value="2">{orderStatus[2].value}</Option>
                    <Option value="3">{orderStatus[3].value}</Option>
                    <Option value="4">{orderStatus[4].value}</Option>
                    <Option value="5">{orderStatus[5].value}</Option>
                    <Option value="6">{orderStatus[6].value}</Option>
                    <Option value="7">{orderStatus[7].value}</Option>
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={4}>
              <Form.Item label="Received">
                {getFieldDecorator('received', {
                  initialValue: ''
                })(
                  <Select>
                    <Option value="">All</Option>
                    <Option value="YES">YES</Option>
                    <Option value="NO">NO</Option>
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col className="gutter-row searchBtn" span={12}>
              <Form.Item>
                <Button htmlType="submit" className="login-form-button searchBtns">
                  Search
                </Button>
              </Form.Item>
              <Form.Item>
                <Button htmlType="reset" onClick={this.handleReset} className="login-form-button resetBtn">
                  Reset
                </Button>
              </Form.Item>
              <Form.Item>
                <Upload {...props}>
                  <Button className="uploadBtn">
                    <Icon type="upload" /> Upload
                  </Button>
                </Upload>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <TableData {...tableProps} />
      </div>
    );
  }
}
export default All;
